<template>
  <div class="create-component-list">
    <div v-for="(item, index) in list" :key="index" class="component-item" @click="onItemClick(item)">
      <h-text v-bind="item"></h-text>
    </div>
  </div>
  <styled-uploader @success="onImageUploaded" />
</template>

<script lang="ts" setup>
import { TextComponentProps, imageDefaultProps } from '@isameng/lowcode-components'
import { ComponentData } from '@/stores/editor'
import { v4 as uuidv4 } from 'uuid'
import { ElMessage } from 'element-plus'
import { getImageDimensions } from '@/utils/utils'

defineProps<{
  list: any[]
}>()
const emits = defineEmits(['onItemClick'])

const onItemClick = (props: TextComponentProps) => {
  const componentData: ComponentData = {
    id: uuidv4(),
    name: 'h-text',
    props
  }
  emits('onItemClick', componentData)
}
const onImageUploaded = (data: { url: string; file: File }) => {
  const componentData: ComponentData = {
    id: uuidv4(),
    name: 'h-image',
    props: {
      ...imageDefaultProps
    }
  }
  ElMessage.success('上传成功')
  componentData.props.src = data.url
  getImageDimensions(data.file).then(({ width }) => {
    console.log(`图片宽度：${width}`)
    const maxWidth = 373
    componentData.props.width = (width > maxWidth ? maxWidth : width) + 'px'
    emits('onItemClick', componentData)
  })
}
</script>
<style lang="scss" scoped>
.component-item {
  width: 100px;
  margin: 0 auto;
  margin-bottom: 15px;
  cursor: pointer;
}
.component-item > * {
  position: static !important;
}
</style>
